// https://stackoverflow.com/questions/68424114/next-js-how-to-fetch-localstorage-data-before-client-side-rendering
// 解决 nextJS 无法获取初始localstorage问题

import { useEffect, useState } from 'react';
import { isSSR } from '../server/utils/isSSR';

function useStorage<T>(
  key: string,
  defaultValue: T | undefined
): [T | undefined, (value: T | undefined) => void, () => void] {
  const [storedValue, setStoredValue] = useState<T | undefined>(
    isSSR
      ? defaultValue
      : localStorage.getItem(key) != undefined
      ? JSON.parse(localStorage.getItem(key) ?? '')
      : defaultValue
  );

  const set = (value: T | undefined) => {
    if (!isSSR) {
      localStorage.setItem(key, JSON.stringify(value));
    }
    if (value == undefined) {
      remove();
    }
    if (value !== storedValue) {
      setStoredValue(value);
    }
  };

  const remove = () => {
    if (!isSSR) {
      localStorage.removeItem(key);
    }
    set(defaultValue ?? undefined);
  };

  useEffect(() => {
    const savedData = localStorage.getItem(key);
    setStoredValue(savedData ? JSON.parse(savedData) : defaultValue);
  }, [key, defaultValue]);

  return [storedValue, set, remove];
}

export default useStorage;
